import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface TabItem {
  title: string      // 标签页标题
  path: string       // 路由路径
  name: string       // 唯一标识名称
  closable: boolean  // 是否可关闭
}

export const useTabStore = defineStore('tab', () => {
  // 存储所有打开的tab页签
  const tabList = ref<TabItem[]>([
    {
      title: '首页',
      path: '/home/dashboard',
      name: 'dashboard',
      closable: false
    }
  ])
  
  // 当前激活的tab页签
  const activeTab = ref('dashboard')
  
  // 添加tab页签
  const addTab = (tab: TabItem) => {
    // 检查是否已存在相同path的页签
    const isExist = tabList.value.some(item => item.path === tab.path)
    if (!isExist) {
      tabList.value.push(tab)
    }
    activeTab.value = tab.name
  }
  
  // 关闭tab页签
  const closeTab = (tabName: string) => {
    const index = tabList.value.findIndex(item => item.name === tabName)
    if (index !== -1) {
      // 如果关闭的是当前激活的页签，则需要激活其他页签
      if (activeTab.value === tabName) {
        // 优先激活右侧页签，如果没有则激活左侧页签
        if (index < tabList.value.length - 1) {
          activeTab.value = tabList.value[index + 1].name
        } else {
          activeTab.value = tabList.value[index - 1].name
        }
      }
      tabList.value.splice(index, 1)
    }
  }
  
  // 设置当前激活的页签
  const setActiveTab = (tabName: string) => {
    activeTab.value = tabName
  }
  
  return {
    tabList,
    activeTab,
    addTab,
    closeTab,
    setActiveTab
  }
})